package GameServer.net;

import GameServer.Demo;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.Properties;

/**
 * Created by gzhd on 2017/11/29.
 * 网络接入模块
 */
public class Netmodule {
    private static Netmodule netModule = null;
    public static Properties properties;
    public static String ip;
    public static int port;
    public static NetFramework netFramework;

    public static Netmodule getInstance() {
        if (netModule == null) {
            netModule = new Netmodule();
            netModule.init();
        }

        return netModule;
    }


    private Netmodule() {

    }


    private void init() {
        try {
            properties = readProperies();
            ip = properties.getProperty("ip");
            port = Integer.parseInt(properties.getProperty("port"));
            netFramework = NetFramework.buildNetFramework(ip, port);
            NetHandler handler = new NethandlerImpl();
            netFramework.setHandler(handler);

        } catch (Exception e) {
            Demo.print("网络配置文件读取错语");
        }
    }
//    GameServer/net/net.properties
    private Properties readProperies() throws IOException {
        Properties p = new Properties();
        InputStream in = Netmodule.class.getResourceAsStream("net.properties");
        Reader r = new InputStreamReader(in, Charset.forName("UTF-8"));
        p.load(r);
        in.close();
        return p;
    }


    public boolean shutNet() {
        try {
            netFramework.shut();
            Demo.print("服务器IP"+ip+"关闭网络成功");
            Demo.print("已解绑端口"+port);
        } catch (Exception e) {
            Demo.print("服务器IP"+ip+"关闭网络失败");
        }

        return true;
    }

    public boolean startNet() {

        try {
            netFramework.start();
            Demo.print("服务器IP"+ip+"开启网络成功");
            Demo.print("已绑定端口"+port);
        } catch (Exception e) {
            e.printStackTrace();
            Demo.print("服务器IP"+ip+"开启网络失败");
        }
        return true;
    }

}
